import axios from "../../request";

const state = {
  token: null,
  user: null
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
    localStorage.setItem("I-Token", token);
  },
  SET_USER: (state, user) => {
    state.user = user;
  },
  LOGOUT: state => {
    state.token = null;
    localStorage.removeItem("I-Token");
  }
};

const actions = {
  // 登录
  login({ commit }, loginForm) {
    return new Promise(async (resolve, reject) => {
      try {
        let res = await axios.post({
          url: "/user/login",
          data: loginForm
        });

        commit("SET_TOKEN", res.data.token);

        resolve();
      } catch (error) {
        reject(error);
      }
    });
  },
  // 登出
  logout({ commit }) {
    commit("LOGOUT");

    document.location.reload();
  },
  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise(async (resolve, reject) => {
      try {
        let info = await axios.post({
          url: "/user/get-info"
        });

        console.log(info);

        commit("SET_USER", info.data);

        resolve(info.data);
      } catch (error) {
        reject();
      }
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
